package com.ailot.cloud.base.data.datascope;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.ailot.cloud.base.common.constants.CommonConstant;
import com.ailot.cloud.base.common.constants.SecurityConstant;
import com.ailot.cloud.base.common.exception.CheckedException;
import com.ailot.cloud.base.data.enums.DataScopeTypeEnum;
import com.ailot.cloud.base.security.model.JwtUser;
import com.ailot.cloud.base.security.utils.SecurityUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.schema.Column;
import org.springframework.security.core.GrantedAuthority;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author litao
 */
public class DataScopeHandler implements DataPermissionHandler {

    private final DataScopeProperties dataScopeProperties;

    private final DataSource dataSource;


    public DataScopeHandler(DataScopeProperties dataScopeProperties, DataSource dataSource) {
        this.dataScopeProperties = dataScopeProperties;
        this.dataSource = dataSource;
    }

    @SneakyThrows
    @Override
    public Expression getSqlSegment(Expression where, String mappedStatementId) {
        //查询需要配置数据权限的方法
        List<String> mapperIds = dataScopeProperties.getMapperIds();
        if (CollUtil.isEmpty(mapperIds)) {
            return where;
        } else {
            if (!CollUtil.contains(mapperIds, mappedStatementId)) {
                return where;
            }
        }
        List<String> orgIds = new ArrayList<>();
        JwtUser user = SecurityUtil.getUser().get();
        if (user == null) {
            throw new CheckedException("用户信息为空");
        }
        //获取角色ID列表
        List<String> roleIdList = user.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .filter(authority -> authority.startsWith(SecurityConstant.ROLE))
                .map(authority -> authority.split("_")[1])
                .collect(Collectors.toList());

        // 获取角色信息
        Entity query = Db.use(dataSource)
                .query("SELECT * FROM " + CommonConstant.UPMS_DATABASE + ".sys_role where id IN ('" + CollUtil.join(roleIdList, "','") + "')")
                .stream().min(Comparator.comparingInt(o -> o.getInt("ds_type"))).get();
        Integer dsType = query.getInt("ds_type");
        //查询全部
        if (DataScopeTypeEnum.ALL.getType() == dsType) {
            return where;
        }
        // 自定义
        if (DataScopeTypeEnum.CUSTOM.getType() == dsType) {
            //部门范围
            String dsScope = query.getStr("ds_scope");
            orgIds.addAll(Arrays.stream(dsScope.split(",")).map(String::toString).collect(Collectors.toList()));
        }
        // 只查询本级
        if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
            orgIds.add(user.getOrgId());
        }
        ItemsList itemsList = new ExpressionList(orgIds.stream().map(StringValue::new).collect(Collectors.toList()));
        InExpression inExpression = new InExpression(new Column(CommonConstant.ORG_SCOPE), itemsList);
        return ObjectUtils.isNotEmpty(where) ? new AndExpression(where, inExpression) : inExpression;
    }
}
